const state = {
    tree: {
        id: 'root',
        title: '根目录',
        apiList: [],
        folderList: [],
    },
    closeAllFolder: 0,
    apiObject: {},
    folderObject: {},
    // folderArray: [],
    moveActiveObject: null,
    markSetting: {
        id: null,
        x: -100,
        y: -100,
        title: '',
    },
    folderMoveModule: false,
    apiMoveModule: false,
    apiMoveType: null,
    folderDetail: {
        object: null,
        drawer: false,
    },
    newFolder: {
        object: null,
        drawer: false,
    },
};
const getters = {};
const mutations = {};

var getIndexArray = function (obj, key) {
    var indexArray = [];
    for (let i = 0; i < obj[key].length; i++) {
        const element = obj[key][i].id;
        indexArray.push(element);
    };
    indexArray = indexArray.join(';');
    return indexArray;
};


const actions = {
    // 渲染无极列表
    renderTree(context, renderData) {

        let apiObject = {};
        let folderObject = {};

        let rootFolder = {};

        let apiList = renderData.apiList;
        let folderList = renderData.folderList;

        for (let i = 0; i < apiList.length; i++) {
            const api = apiList[i];
            apiObject[api.id] = api;
        };

        for (let i = 0; i < folderList.length; i++) {
            const folder = folderList[i];
            folderObject[folder.id] = folder;

            folder.childFolders = {};
            folder.childApis = {};
        };

        for (let i = 0; i < folderList.length; i++) {
            const folder = folderList[i];
            if (folder.folderParentId) {
                folderObject[folder.folderParentId].childFolders[folder.id] = folder;
            } else {
                rootFolder = folder;
            }
        };

        for (let i = 0; i < apiList.length; i++) {
            const api = apiList[i];
            folderObject[api.apiFolderId].childApis[api.id] = api;
        };

        for (const key in folderObject) {
            if (folderObject.hasOwnProperty(key)) {
                const folder = folderObject[key];
                if (!folder.folderList) {
                    folder.folderList = [];
                };
                if (!folder.apiList) {
                    folder.apiList = [];
                };
                if (folder.folderIndexArray) {
                    let folderIndexArray = folder.folderIndexArray.split(';');
                    for (let i = 0; i < folderIndexArray.length; i++) {
                        const childFolderId = folderIndexArray[i];
                        if (folder.childFolders.hasOwnProperty(childFolderId)) {
                            let childFolder = folder.childFolders[childFolderId];
                            folder.folderList.push(childFolder);
                            delete folder.childFolders[childFolderId];
                        };
                    }
                };
                for (const key in folder.childFolders) {
                    if (folder.childFolders.hasOwnProperty(key)) {
                        const childFolder = folder.childFolders[key];
                        folder.folderList.push(childFolder);
                    }
                };
                if (folder.childIndexArray) {
                    let childIndexArray = folder.childIndexArray.split(';');
                    for (let i = 0; i < childIndexArray.length; i++) {
                        const childApiId = childIndexArray[i];
                        if (folder.childApis.hasOwnProperty(childApiId)) {
                            let childApi = folder.childApis[childApiId];
                            folder.apiList.push(childApi);
                            delete folder.childApis[childApiId];
                        };
                    }
                };
                for (const key in folder.childApis) {
                    if (folder.childApis.hasOwnProperty(key)) {
                        const childApi = folder.childApis[key];
                        folder.apiList.push(childApi);
                    }
                };
            }
        };
        context.state.apiObject = apiObject;
        context.state.folderObject = folderObject;

        rootFolder.isRoot = true;
        context.state.tree = rootFolder;
    },
    // context.dispatch('getUserTagList');
    getRenderData(context, callback) {
        // action=> 获取所有API数据
        window.action.api.getRenderData().then((res) => {
            if (res) {
                context.dispatch('renderTree', res);
                if (callback) {
                    callback();
                };
            };
            // context.dispatch('renderTree', JSON.parse(JSON.stringify(TestData)));
        });
    },
    getTree(context, callback) {
        callback(JSON.parse(JSON.stringify(context.state.tree)));
    },
    // 全局通知API移动模式
    setApiMoveModule(context, type) {
        context.state.apiMoveModule = type;
    },
    // 监听鼠标移动，更改Mark层数据
    setMoveObject(context, obj) {
        context.state.markSetting = obj;
    },
    // 当前元素对象
    setMoveActiveObject(context, obj) {
        context.state.moveActiveObject = obj;
    },
    // 全局通知 文件夹 移动模式
    setFolderMoveModule(context, type) {
        context.state.folderMoveModule = type;
    },
    // 缓存API移动类型
    setApiMoveType(context, type) {
        context.state.apiMoveType = type;
    },
    async checkMove(context) {
        if (!context.state.apiMoveType) {
            return;
        };
        if (!context.state.moveActiveObject) {
            return;
        };
        if (context.state.apiMoveModule) { // api 移动模式
            if (context.state.apiMoveType == 'moveIntoFolder') { // 移动到文件夹中
                let oldObj = context.state.apiObject[context.state.markSetting.id];
                let oldFolder = context.state.folderObject[oldObj.apiFolderId];
                let newFolder = context.state.moveActiveObject;

                let oldIndex = 0;
                for (let i = 0; i < oldFolder.apiList.length; i++) {
                    let apiObj = oldFolder.apiList[i];
                    if (apiObj.id == oldObj.id) {
                        oldIndex = i
                        break;
                    };
                };
                if (oldIndex == 0 && oldFolder.id == newFolder.id) {
                    return
                };

                oldFolder.apiList.splice(oldIndex, 1);

                let oldChildIndexArray = [];
                for (let i = 0; i < oldFolder.apiList.length; i++) {
                    const element = oldFolder.apiList[i].id;
                    oldChildIndexArray.push(element);
                }
                oldChildIndexArray = oldChildIndexArray.join(';');
                // console.log(oldFolder.id, oldChildIndexArray);

                oldObj.apiFolderId = newFolder.id;
                newFolder.apiList.splice(0, 0, oldObj);

                let newChildIndexArray = [];
                for (let i = 0; i < newFolder.apiList.length; i++) {
                    const element = newFolder.apiList[i].id;
                    newChildIndexArray.push(element);
                }
                newChildIndexArray = newChildIndexArray.join(';');
                // console.log(newFolder.id, newChildIndexArray);

                // action=> 更新API排序
                window.action.api.updataApiOrderByDifferent({
                    id: oldObj.id,
                    from: {
                        index: oldChildIndexArray,
                        id: oldFolder.id,
                    },
                    to: {
                        index: newChildIndexArray,
                        id: newFolder.id,
                    },
                });

                return;
            };

            let apiMoveType = context.state.apiMoveType.toString();
            let newObj = context.state.moveActiveObject;
            let oldObj = context.state.apiObject[context.state.markSetting.id];
            let newFolder = context.state.folderObject[newObj.apiFolderId];
            let oldFolder = context.state.folderObject[oldObj.apiFolderId];

            if (newFolder === oldFolder) { // 同文件夹移动
                let oldIndex = 0;
                for (let i = 0; i < newFolder.apiList.length; i++) {
                    const apiObj = newFolder.apiList[i];
                    if (apiObj.id == oldObj.id) {
                        oldIndex = i
                        break;
                    };
                };
                let newIndex = 0;
                for (let i = 0; i < newFolder.apiList.length; i++) {
                    const apiObj = newFolder.apiList[i];
                    if (apiObj.id == newObj.id) {
                        newIndex = i
                        break;
                    };
                };
                if (oldIndex == newIndex) {
                    return
                };
                newFolder.apiList.splice(oldIndex, 1);
                if (apiMoveType == 'TopMoveMark') {
                    newFolder.apiList.splice(newIndex, 0, oldObj);
                } else if (apiMoveType == 'BottomMoveMark') {
                    newFolder.apiList.splice(newIndex + 1, 0, oldObj);
                };
                let childIndexArray = [];
                for (let i = 0; i < newFolder.apiList.length; i++) {
                    const element = newFolder.apiList[i].id;
                    childIndexArray.push(element);
                }
                childIndexArray = childIndexArray.join(';');

                // action=> 更新API排序
                window.action.api.updataApiOrderBySame({
                    index: childIndexArray,
                    id: newFolder.id,
                });


            } else if (newFolder !== oldFolder) {  // 异文件夹移动
                let oldIndex = 0;
                for (let i = 0; i < oldFolder.apiList.length; i++) {
                    let apiObj = oldFolder.apiList[i];
                    if (apiObj.id == oldObj.id) {
                        oldIndex = i
                        break;
                    };
                };
                oldFolder.apiList.splice(oldIndex, 1);

                let oldChildIndexArray = [];
                for (let i = 0; i < oldFolder.apiList.length; i++) {
                    const element = oldFolder.apiList[i].id;
                    oldChildIndexArray.push(element);
                }
                oldChildIndexArray = oldChildIndexArray.join(';');
                // console.log(oldFolder.id, oldChildIndexArray);

                let newIndex = 0;
                for (let d = 0; d < newFolder.apiList.length; d++) {
                    let apiObj = newFolder.apiList[d];
                    if (apiObj.id == newObj.id) {
                        newIndex = d
                        break;
                    };
                };
                if (apiMoveType == 'TopMoveMark') {
                    newFolder.apiList.splice(newIndex, 0, oldObj);
                } else if (apiMoveType == 'BottomMoveMark') {
                    newFolder.apiList.splice(newIndex + 1, 0, oldObj);
                };
                oldObj.apiFolderId = newFolder.id;

                let newChildIndexArray = [];
                for (let i = 0; i < newFolder.apiList.length; i++) {
                    const element = newFolder.apiList[i].id;
                    newChildIndexArray.push(element);
                }
                newChildIndexArray = newChildIndexArray.join(';');
                // console.log(newFolder.id, newChildIndexArray);

                // action=> 更新API排序
                window.action.api.updataApiOrderByDifferent({
                    id: oldObj.id,
                    from: {
                        index: oldChildIndexArray,
                        id: oldFolder.id,
                    },
                    to: {
                        index: newChildIndexArray,
                        id: newFolder.id,
                    },
                });
            };
        } else if (context.state.folderMoveModule) {
            if (context.state.apiMoveType == 'intoFolder') { // 移动到文件夹中

                let oldObj = context.state.folderObject[context.state.markSetting.id];
                let oldFolder = context.state.folderObject[oldObj.folderParentId];
                let newFolder = context.state.moveActiveObject;

                let oldIndex = 0;
                for (let i = 0; i < oldFolder.folderList.length; i++) {
                    let apiObj = oldFolder.folderList[i];
                    if (apiObj.id == oldObj.id) {
                        oldIndex = i
                        break;
                    };
                };
                if (oldIndex == 0 && oldFolder.id == newFolder.id) {
                    return
                };

                oldFolder.folderList.splice(oldIndex, 1);
                var oldChildIndexArray = getIndexArray(oldFolder, 'folderList');
                oldObj.folderParentId = newFolder.id;
                newFolder.folderList.splice(0, 0, oldObj);
                var newChildIndexArray = getIndexArray(newFolder, 'folderList');

                // action=> 移动文件夹(不同文件夹)
                window.action.api.updataFolderOrderByInto({
                    fromFolder: { id: oldFolder.id, index: oldChildIndexArray },
                    moveFolder: { id: oldObj.id, parent: newFolder.id },
                    toFolder: { id: newFolder.id, index: newChildIndexArray }
                });

                return;
            };

            let apiMoveType = context.state.apiMoveType.toString();
            let newObj = context.state.moveActiveObject;
            let oldObj = context.state.folderObject[context.state.markSetting.id];
            let newFolder = context.state.folderObject[newObj.folderParentId];
            let oldFolder = context.state.folderObject[oldObj.folderParentId];


            if (newFolder === oldFolder) { // 同文件夹移动
                let oldIndex = 0;
                for (let i = 0; i < newFolder.folderList.length; i++) {
                    const apiObj = newFolder.folderList[i];
                    if (apiObj.id == oldObj.id) {
                        oldIndex = i
                        break;
                    };
                };
                let newIndex = 0;
                for (let i = 0; i < newFolder.folderList.length; i++) {
                    const apiObj = newFolder.folderList[i];
                    if (apiObj.id == newObj.id) {
                        newIndex = i
                        break;
                    };
                };
                if (oldIndex == newIndex) {
                    return
                };
                newFolder.folderList.splice(oldIndex, 1);
                if (apiMoveType == 'TopMoveMark') {
                    newFolder.folderList.splice(newIndex, 0, oldObj);
                } else if (apiMoveType == 'BottomMoveMark') {
                    newFolder.folderList.splice(newIndex + 1, 0, oldObj);
                };
                var childIndexArray = getIndexArray(newFolder, 'folderList');

                // action=> 移动文件夹(相同文件夹)
                window.action.api.updateFolderOrderBySame({ id: newFolder.id, index: childIndexArray });

            } else if (newFolder !== oldFolder) {  // 异文件夹移动
                let oldIndex = 0;
                for (let i = 0; i < oldFolder.folderList.length; i++) {
                    let apiObj = oldFolder.folderList[i];
                    if (apiObj.id == oldObj.id) {
                        oldIndex = i
                        break;
                    };
                };
                oldFolder.folderList.splice(oldIndex, 1);

                let oldChildIndexArray = getIndexArray(oldFolder, 'folderList');
                let newIndex = 0;
                for (let d = 0; d < newFolder.folderList.length; d++) {
                    let apiObj = newFolder.folderList[d];
                    if (apiObj.id == newObj.id) {
                        newIndex = d
                        break;
                    };
                };
                if (apiMoveType == 'TopMoveMark') {
                    newFolder.folderList.splice(newIndex, 0, oldObj);
                } else if (apiMoveType == 'BottomMoveMark') {
                    newFolder.folderList.splice(newIndex + 1, 0, oldObj);
                };
                oldObj.folderParentId = newFolder.id;

                let newChildIndexArray = getIndexArray(newFolder, 'folderList');
                // action=> 移动文件夹(不同文件夹)
                window.action.api.updataFolderOrderByInto({
                    fromFolder: { id: oldFolder.id, index: oldChildIndexArray },
                    moveFolder: { id: oldObj.id, parent: newFolder.id },
                    toFolder: { id: newFolder.id, index: newChildIndexArray }
                });
            };
        }
    },
    openFolderDetail(context, value) {
        context.state.folderDetail.object = value;
        context.state.folderDetail.drawer = true;
    },
    editFolderDetail(context, data) {
        context.state.folderDetail.object.title = data.title;
        context.state.folderDetail.object.description = data.description;
        context.dispatch('closeFolderDetail');
    },
    closeFolderDetail(context) {
        context.state.folderDetail.object = null;
        context.state.folderDetail.drawer = false;
    },
    newFolder(context, value) {
        context.state.newFolder.object = value;
        context.state.newFolder.drawer = true;
    },
    closeNewFolder(context) {
        context.state.newFolder.object = null;
        context.state.newFolder.drawer = false;
    },
    newFolderEvent(context, folderMessage) {
        var oldFolder = context.state.newFolder.object;
        var newFolderArray = [];
        for (let index = 0; index < oldFolder.folderList.length; index++) {
            const folder = oldFolder.folderList[index];
            newFolderArray.push(folder.folderId);
        };

        // action=> 创建文件夹
        window.action.api.creatFolder({
            title: folderMessage.title,
            description: folderMessage.description,
        }, {
            folderId: oldFolder.folderId,
            newFolderArray: newFolderArray
        }).then((res) => {
            if (res) {
                context.state.newFolder.object = null;
                context.state.newFolder.drawer = false;
                context.dispatch('getRenderData');
            };
        });
    },
    closeAllFolder(context) {
        context.state.closeAllFolder++;
    },
    creatApi(context, value) {
        var folderId = value.folderId;
        var folder = context.state.folderObject[folderId];
        var oldApiArray = [];
        for (let i = 0; i < folder.apiList.length; i++) {
            const api = folder.apiList[i];
            oldApiArray.push(api.id);
        };
        let data = {
            folderId: folderId,
            title: value.apiData.title,
            type: value.apiData.type,
            status: value.apiData.status,
            description: value.apiData.description,
            url: value.apiData.url,
            param: JSON.stringify({
                bodyType: value.apiData.bodyType,
                header: value.apiData.header,
                body: value.apiData.body,
                fromdata: value.apiData.fromdata,
                query: value.apiData.query,
                rest: value.apiData.rest,
                before: value.apiData.before,
                after: value.apiData.after,
                response: value.apiData.response,
            }).replace(/\'/g, "&apos;"),
            oldApiArray: oldApiArray
        };
        // action=> 创建API
        window.action.api.creatApi(data).then((res) => {
            if (res) {
                context.dispatch('getRenderData', () => {
                    if (value.callback) {
                        value.callback(res);
                    }
                });
            }
        });
    },
    updataApi(context, value) {
        let data = {
            id: value.id,
            title: value.apiData.title,
            type: value.apiData.type,
            status: value.apiData.status,
            description: value.apiData.description,
            url: value.apiData.url,
            param: JSON.stringify({
                bodyType: value.apiData.bodyType,
                header: value.apiData.header,
                body: value.apiData.body,
                fromdata: value.apiData.fromdata,
                query: value.apiData.query,
                rest: value.apiData.rest,
                before: value.apiData.before,
                after: value.apiData.after,
                response: value.apiData.response,
            }),
        };
        // action=> 更新API
        window.action.api.updataApi(data).then((res) => {
            if (res) {
                context.dispatch('getRenderData', () => {
                    if (value.callback) {
                        value.callback(res);
                    }
                });
            }
        });
    },
    deleteApi(context, value) {
        // action=> 删除API
        window.action.api.deleteApi(value.id).then((res) => {
            if (res) {
                context.dispatch('getRenderData', () => {
                    if (value.callback) {
                        value.callback();
                    }
                });
            }
        });
    },
    deleteFolder(context, value) {
        // action=> 删除文件夹
        window.action.api.deleteFolder(value).then((res) => {
            if (res) {
                context.dispatch('getRenderData');
            }
        });
    },
};

export default {
    namespaced: true,
    state,
    getters,
    mutations,
    actions
}